package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Menu;
import com.example.entity.User;
import com.example.service.MenuService;
import com.example.service.RoleService;
import com.example.utils.TreeNode;
import com.example.utils.TreeNodeBuilder;
import com.example.vo.DataView;
import com.example.vo.MenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.*;


@RestController
@RequestMapping("/menu")
public class MenuController {


    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;


    @RequestMapping("/loadAllMenu")
    public DataView loadAllMenu(MenuVo menuVo){
        IPage<Menu> page=new Page<>(menuVo.getPage(), menuVo.getLimit());
        QueryWrapper<Menu> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(menuVo.getTitle()),"title",menuVo.getTitle());
        queryWrapper.orderByAsc("ordernum");
        menuService.page(page,queryWrapper);
        return new DataView(page.getTotal(),page.getRecords());
    }


    /**
     * 加载下拉菜单数据 初始化下拉树
     * @return
     */
    @RequestMapping("/loadMenuManagerLeftTreeJson")
    public DataView loadMenuManagerLeftTreeJson(){
        List<Menu> list = menuService.list();
        List<TreeNode> treeNodes = new ArrayList<>();
        for( Menu menu:list){
            Boolean open = menu.getOpen() == 1 ? true:false;
            treeNodes.add(new TreeNode(menu.getId(), menu.getPid(), menu.getTitle(), open));
        }
        return new DataView(treeNodes);
    }


    /**
     * 赋值最大的排序码+1
     * 条件查询倒序排序，取一条数据，+1
     */
    @RequestMapping("/loadMenuMaxOrderNum")
    public Map<String,Object> loadMenuMaxOrderNum(){
        Map<String, Object> map= new HashMap<>();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderByDesc("ordernum");
        IPage<Menu> page=new Page<>(1,1);
        List<Menu> list = menuService.page(page, queryWrapper).getRecords();
        map.put("value",list.get(0).getOrdernum()+1);
        return map;
    }

    /**
     * 新增菜单
     */
    @RequestMapping("/addMenu")
    public DataView addMenu(Menu menu){
        DataView dataView=new DataView();
        menu.setType("menu");
        boolean save = menuService.save(menu);
        if(!save){
            dataView.setMsg("菜单插入失败");
            dataView.setCode(100);
        }else{
            dataView.setMsg("菜单插入成功");
            dataView.setCode(200);
        }
        return dataView;
    }

    /**
     * 更新菜单
     * @return
     */
    @RequestMapping("/updateMenu")
    public DataView updateMenu(Menu menu){
        menuService.updateById(menu);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("更新菜单成功");
        return dataView;
    }

    /**
     * 判断当前菜单有没有孩子结点
     */
    @RequestMapping("/checkMenuHasChildrenNode")
    public Map<String,Object> checkMenuHasChildrenNode(Menu menu){
        Map<String,Object> map=new HashMap<>();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("pid",menu.getId());
        List list = menuService.list(queryWrapper);
        if(list.size()>0)
            map.put("value",true);
        else
            map.put("value",false);
        return map;
    }

    /**
     * 删除菜单
     * @param menu
     * @return
     */
    @RequestMapping("/deleteMenu")
    public DataView deleteMenu(Menu menu){
        DataView dataView=new DataView();
        menuService.removeById(menu.getId());
        dataView.setMsg("删除菜单成功");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 加载主页面index的菜单栏。带有层级关系
     * 不同用户登录看到不同菜单栏  session---用户id--角色List<RoleId>---菜单List<MenuId>
     */
    @RequestMapping("/loadIndexLeftMenuJson")
    public DataView loadIndexLeftMenuJson(Menu menu, HttpSession session){
        List<Menu> list = null;

        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();

        if (user.getUsername().equals("admin") || StringUtils.equals(user.getUsername(),"admin")){
            list= menuService.list();
        }else { //不是超级管理员
            //根据用户id查询角色id
            List<Integer> currentUserRoleIds = roleService.queryUserRoleById(userId);
            //根据角色id查询菜单栏
            Set<Integer> mids = new HashSet<>();  //使用set进行去重
            for (Integer rid : currentUserRoleIds) {
                List<Integer> currentRolePermissionIds = roleService.queryAllPermissionByRid(rid);
                mids.addAll(currentRolePermissionIds);
            }
            if (mids.size() > 0) {
                QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id", mids);
                list = menuService.list(queryWrapper);
            }
        }

        //使用小工具构造层级关系
        List<TreeNode> treeNodes=new ArrayList<>();
        for (Menu m : list) {
            Integer id = m.getId();
            Integer pid=m.getPid();
            String title = m.getTitle();
            String icon = m.getIcon();
            String href = m.getHref();
            Boolean open = m.getOpen().equals(1)?true:false;
            treeNodes.add(new TreeNode(id,pid,title,icon,href,open));
        }

        //构造层级关系
        List<TreeNode> nodeList = TreeNodeBuilder.build(treeNodes, 0);
        return new DataView(nodeList);
    }
}
